<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- 题目 -->
      <el-form-item label="题目" prop="questionName">
        <el-input
          v-model="queryParams.questionName"
          placeholder="请输入题目关键词"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 题型 -->
      <el-form-item label="题型" prop="questionType">
        <el-select
          v-model="queryParams.questionType"
          placeholder="请选择题型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.question_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 关联状态 -->
      <el-form-item label="关联状态" prop="relateStatus">
        <el-select
          v-model="queryParams.relateStatus"
          placeholder="请选择关联状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.relate_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 创建时间 -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- 左侧功能按钮 -->
      <el-col :span="24">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <!-- 左侧按钮组 -->
          <div style="display: flex; gap: 10px">
            <el-button type="warning" plain @click="handleExport"
              >导出</el-button
            >
            <el-button
              type="primary"
              plain
              :disabled="single"
              @click="handleUpdate"
              >编辑题目</el-button
            >
            <el-button type="success" plain @click="handleCreateQuestion"
              >创建题目</el-button
            >
            <el-button type="info" plain @click="handleImport"
              >导入题目</el-button
            >
            <el-button
              type="danger"
              plain
              :disabled="single"
              @click="handleRelate"
              >关联题库</el-button
            >
            <el-button
              type="danger"
              plain
              :disabled="multiple"
              @click="handleDelete"
              >删除题目</el-button
            >
          </div>

          <!-- 右侧操作按钮 -->
          <div style="display: flex; gap: 10px">
            <column-config-dialog-vue
              :showSearch.sync="showSearch"
              :columns="tableColumns"
              @queryTable="getList"
            ></column-config-dialog-vue>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="questionList"
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" align="center" />

      <!-- 动态列 -->
      <template v-for="column in tableColumns">
        <el-table-column
          v-if="column.visible"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          align="center"
        >
          <!-- 特殊列处理 -->
          <template slot-scope="scope">
            <!-- 题型 -->
            <dict-tag
              v-if="column.prop === 'questionType'"
              :options="dict.type.question_type"
              :value="scope.row[column.prop]"
            />
            <!-- 关联状态 -->
            <dict-tag
              v-else-if="column.prop === 'relateStatus'"
              :options="dict.type.relate_status"
              :value="scope.row[column.prop]"
            />
            <!-- 操作列 -->
            <template v-else-if="column.prop === 'operation'">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['examination:question:edit']"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleRelateRow(scope.row)"
                >关联题库</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['examination:question:remove']"
                >删除</el-button
              >
            </template>
            <!-- 普通列 -->
            <span v-else>{{ scope.row[column.prop] }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="试题名称" prop="questionName">
          <el-input
            v-model="form.questionName"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="1:单选题, 2:多选题, 3:判断题" prop="questionType">
          <el-select
            v-model="form.questionType"
            placeholder="请选择1:单选题, 2:多选题, 3:判断题"
          >
            <el-option
              v-for="dict in dict.type.question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联状态" prop="relateStatus">
          <el-select v-model="form.relateStatus" placeholder="请选择关联状态">
            <el-option
              v-for="dict in dict.type.relate_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联题组ID" prop="relateGroupId">
          <el-input
            v-model="form.relateGroupId"
            placeholder="请输入关联题组ID"
          />
        </el-form-item>
        <el-form-item label="关联题组名称" prop="relateGroupName">
          <el-input
            v-model="form.relateGroupName"
            placeholder="请输入关联题组名称"
          />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="form.answer" placeholder="请输入答案" />
        </el-form-item>
        <el-form-item label="答案解析">
          <editor v-model="form.analysisContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="是否删除" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入是否删除" />
        </el-form-item>
        <el-form-item label="${comment}" prop="exampleOne">
          <el-input v-model="form.exampleOne" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="${comment}" prop="exampleTwo">
          <el-input v-model="form.exampleTwo" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="${comment}" prop="exampleThree">
          <el-input
            v-model="form.exampleThree"
            placeholder="请输入${comment}"
          />
        </el-form-item>
        <el-form-item label="${comment}" prop="exampleFour">
          <el-input v-model="form.exampleFour" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="${comment}" prop="exampleFive">
          <el-input v-model="form.exampleFive" placeholder="请输入${comment}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 创建题目 -->
    <CreateQuestionDialogVue
      ref="createDialog"
      :visible.sync="showCreateDialog"
      @submit="handleAddSubmit"
      @submitNext="handleAddSubmitNext"
    />
    <!-- 编辑题目 -->
    <EditQuestionDialogVue
      ref="editDialog"
      :visible.sync="showEditDialog"
      :question-data="currentQuestion"
      @submit="handleEditSubmit"
    />
    <!-- 导入题目 -->
    <ImportQuestionDialogVue
      ref="importDialog"
      :visible.sync="importVisible"
      @success="getList"
    />
    <!-- 关联题库 -->
    <RelateQuestionDialogVue
      ref="relateDialog"
      :visible.sync="relateVisible"
      :dict="dictCache"
      :question-id="selectedId"
      :question-type="questionType"
      @confirm="onConfirm"
    />
  </div>
</template>

<script>
import {
  listQuestion,
  getQuestion,
  delQuestion,
  addQuestion,
  updateQuestion,
  getListInfo,
  associationGroup,
} from "@/api/examination/question";
// 列配置
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
// 创建题目
import CreateQuestionDialogVue from "../../../components/examination/CreateQuestionDialog.vue";
// 导入题目
import ImportQuestionDialogVue from "../../../components/examination/ImportQuestionDialog.vue";
// 关联题库
import RelateQuestionDialogVue from "../../../components/examination/RelateQuestionGroupDialog.vue";
// 编辑题目
import EditQuestionDialogVue from "../../../components/examination/EditQuestionDialog.vue";
export default {
  name: "Question",
  components: {
    ColumnConfigDialogVue,
    CreateQuestionDialogVue,
    ImportQuestionDialogVue,
    RelateQuestionDialogVue,
    EditQuestionDialogVue,
  },
  dicts: ["question_type", "relate_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题管理表格数据
      questionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionName: null,
        questionType: null,
        relateStatus: null,
        relateGroupName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      //新增数据定义
      //列显隐
      tableColumns: [
        { prop: "questionType", label: "题型", visible: true },
        { prop: "questionName", label: "题目", visible: true },
        { prop: "relateGroupName", label: "关联题组", visible: true },
        { prop: "createBy", label: "创建人", visible: true },
        { prop: "createTime", label: "创建时间", visible: true },
        { prop: "operation", label: "操作", visible: true },
      ],
      //创建题目
      showCreateDialog: false,
      //导入题目
      importVisible: false,
      //关联题库
      relateVisible: false,
      selectedId: "", // 存储选中的题目ID数组
      questionType: "",
      // 缓存字典数据
      dictCache: {
        question_type: {},
        relate_status: {},
      },
      // 编辑题目
      showEditDialog: false,
      currentQuestion: {}, // 当前编辑的题目数据
    };
  },
  created() {
    this.getList();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
  },
  methods: {
    async loadDicts() {
      this.dictCache.question_type = this.dict.label.question_type;
      this.dictCache.relate_status = this.dict.label.relate_status;
    },
    /** 查询试题管理列表 */
    getList() {
      this.loading = true;
      getListInfo(this.queryParams).then((response) => {
        this.questionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        questionId: null,
        questionName: null,
        questionType: null,
        relateStatus: null,
        relateGroupId: null,
        relateGroupName: null,
        answer: null,
        analysisContent: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
        exampleFour: null,
        exampleFive: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 将时间范围拆分为 start 和 end
      if (this.queryParams.createTime) {
        this.queryParams.createStartTime = this.queryParams.createTime[0];
        this.queryParams.createEndTime = this.queryParams.createTime[1];
        this.queryParams.createTime = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.createTime = null;
      this.queryParams.createStartTime = null;
      this.queryParams.createEndTime = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.questionId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const questionId = row.questionId || this.ids;
      getQuestion(questionId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试题管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.questionId != null) {
            updateQuestion(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuestion(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const questionIds = row.questionId || this.ids;
      this.$modal
        .confirm('是否确认删除试题管理编号为"' + questionIds + '"的数据项？')
        .then(function () {
          return delQuestion(questionIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "examination/question/export",
        {
          ...this.queryParams,
        },
        `question_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法部分

    //创建题目
    handleCreateQuestion() {
      this.showCreateDialog = true;
    },
    handleAddSubmit(data) {
      //新增--提交数据
      console.log(data);
      addQuestion(data).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.showCreateDialog = false;
        this.getList();
      });
    },
    handleAddSubmitNext() {
      //提交数据并继续添加  发送请求后重置表单继续
    },
    //导入题目
    handleImport() {
      this.importVisible = true;
    },
    //关联题库
    handleRelate() {
      // 点击“关联题库”按钮时触发
      if (this.ids.length === 0) {
        this.$modal.msgError("请先选择要关联的题目！");
        return;
      }
      this.relateVisible = true; // 显示弹窗
      // 同时需要将选中的ID传递给弹窗组件

      const selectedRow = this.questionList.find(
        (item) => item.questionId === this.ids[0]
      );

      this.selectedId = selectedRow.questionId; // 同步ids到selectedId
      this.questionType = selectedRow.questionType;
      console.log(selectedRow);
    },
    handleRelateRow(row) {
      this.selectedId = row.questionId; // 将当前行的ID添加到选中数组
      this.questionType = row.questionType;
      this.relateVisible = true; // 显示关联题库弹窗
    },
    onConfirm(groupIds) {
      // 接收子组件返回的选中的题组ID列表
      console.log("选中的题组ID:", groupIds);

      const selectedQuestion = this.questionList.find(
        (item) => item.questionId === this.selectedId
      );
      var params = {
        questionId: selectedQuestion.questionId,
        questionGroupIds: groupIds,
      };
      associationGroup(params).then(() => {
        this.$modal.msgSuccess("关联成功");
        this.relateVisible = false;
        this.getList(); // 刷新列表
      });
    },
    // 编辑题目
    /** 修改按钮操作 */
    handleUpdate(row) {
      const questionId = row.questionId || this.ids[0];
      getQuestion(questionId).then((response) => {
        this.currentQuestion = response.data;
        this.showEditDialog = true;
      });
    },

    /** 编辑题目提交 */
    handleEditSubmit(data) {
      updateQuestion(data).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.showEditDialog = false;
        this.getList();
      });
    },
  },
};
</script>
